/*
 * BaseAdapter.cpp
 *
 *  Created on: 2016-6-29
 *      Author: Administrator
 */

#include "BaseAdapter.h"


#include "cJSON.h"
#include "SyncQueue.h"
#include "Hex.h"
SyncQueue<Packet*> recvJSONQueue;
//int isClose = 0;
volatile MethodBridge brige = NULL;
EXPORT int invokeMethod(char* input, int inputSize,void *client ) {
	LOGI("JSON(%d bytes)->%s",inputSize,input);
	if(brige==NULL){
		LOGW("binder not be found ,are you setMethodBinder?");
		return 0;
	}
	if (input == NULL) {
		LOGW("null Buffer will not be send");
		return 0;
	}

	cJSON* jo2 = cJSON_Parse(input);
	if (jo2 == NULL) {
		LOGW("JSON Parse fail, Not a JSON String");
		return 0;
	}
	if(inputSize>BUF_MAX_SIZE){
		LOGW("inputSize %d >BUF_MAX_SIZE(%d)",inputSize,BUF_MAX_SIZE);
		return 0;
	}
	//
	cJSON* cJsonAction = cJSON_GetObjectItem(jo2, JSON_BRIDGE_METHID);
	if(cJsonAction==NULL){
		LOGW("'action' is not exist");
		return 0;
	}
	//
	int action = cJsonAction->valueint;

	//
	cJSON* cJsonMsg = cJSON_GetObjectItem(jo2, JSON_BRIDGE_PARAMS);
	char* msg = NULL;
	if(cJsonMsg!=NULL){
		msg =cJSON_PrintUnformatted(cJsonMsg);
	}
	int msgLen = (msg==NULL?0:strlen(msg));
	LOGI("action:%d,msg:%s", action, msg);

	//
	cJSON* cJsonBytes = cJSON_GetObjectItem(jo2, JSON_BRIDGE_BYTES);
	char* bytes = NULL;
	if (cJsonBytes == NULL || ((cJsonBytes->type & cJSON_String) != cJSON_String)) {
		LOGI("bytes== NULL||byte not a String");
	}else{
		bytes =cJsonBytes->valuestring;
	}

	//buytesLen
	int buytesLen = (bytes==NULL?0:strlen(bytes));

	if(buytesLen>0&&buytesLen%2==0){
		size_t bytesDataLen = buytesLen;
		LOGI("bytes strlen:%d ->%s", buytesLen,bytes);
		//hex decode
		int lenBytesDataHex = bytesDataLen / 2;
		char bytesDataHexDecode[BUF_MAX_SIZE];
		memset(bytesDataHexDecode, 0, BUF_MAX_SIZE);
		stringToBytes(bytes, bytesDataLen, bytesDataHexDecode,
				lenBytesDataHex);
		brige(action,msg,msgLen,bytesDataHexDecode,lenBytesDataHex,client);
	}else{
		brige(action,msg,msgLen,NULL,0,client);
	}
	return 0;
}
void setMethodBridge(MethodBridge _binder){
	brige = _binder;
}

int handleJsonPacket(handleJson handler) {
	Packet * packet = NULL;
	while ((packet = recvJSONQueue.pop()) != NULL) {
		handler(packet);
		free(packet);
		packet = NULL;
	}
	return 0;
}

int pushMsgToRecvQueue(Packet* packet){
	if(packet!=NULL&&packet->size>0&&packet->size<=BUF_MAX_SIZE){
		std::size_t packetLen = sizeof(Packet);
		Packet *pack = (Packet*)malloc(packetLen);
		if(pack==NULL){
			LOGW("OOM malloc return null");
			return 0;
		}
		memset(pack,0,packetLen);
		memcpy(pack, packet, packetLen);
		if(recvJSONQueue.size()>BUF_MAX_SIZE){
			LOGW("recvJSONQueue.size()> %d",BUF_MAX_SIZE);
			return 0;
		}
		recvJSONQueue.push(packet);
		return 0;
	}else{
		LOGW("recvJson fail, packet!=NULL&&packet->size>0&&packet->size<=BUF_MAX_SIZE ?");
		return 0;
	}
}
